/**
 * 文本输入字段组件
 * 封装Ant Design的Form.Item和Input组件，提供带验证的文本输入功能
 * 支持提示信息、必填验证和最大长度限制
 */
import React, { useMemo } from 'react';
import { Form, Input, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import type { Rule } from 'antd/es/form';

/**
 * 文本字段属性接口
 */
interface TextFieldProps {
  /** 字段名称，对应Form.Item的name属性 */
  name: string;
  /** 字段标签 */
  label?: React.ReactNode;
  /** 是否必填，默认为true */
  required?: boolean;
  /** 输入框占位文本 */
  placeholder?: string;
  /** 最大输入长度限制 */
  maxLength?: number;
  /** 自定义错误提示信息 */
  message?: string;
  /** 字段说明tooltip内容 */
  tooltip?: string;
}

/**
 * 文本输入字段组件实现
 * @param props 组件属性
 * @returns React组件
 */
const TextField: React.FC<TextFieldProps> = ({
  name,
  label,
  required = true,
  placeholder,
  maxLength,
  message,
  tooltip,
}) => {
  // 构建带tooltip的标签
  const labelWithTooltip = tooltip ? (
    <span className="text-field-label-with-tooltip">
      {label}
      <Tooltip title={tooltip}>
        <QuestionCircleOutlined style={{ marginLeft: 8 }} />
      </Tooltip>
    </span>
  ) : label;

  // 构建验证规则
  const rules = useMemo((): Rule[] => {
    const ruleList: Rule[] = [];
    
    // 必填验证规则
    if (required) {
      ruleList.push({
        required: true,
        message: message || (label ? `请输入${label}` : '此项为必填项'),
        type: 'string'
      });
    }
    
    // 最大长度验证规则
    if (maxLength !== undefined) {
      ruleList.push({
        max: maxLength,
        message: `最多输入${maxLength}个字符`,
        type: 'string'
      });
    }
    
    return ruleList;
  }, [required, message, label, maxLength]);

  return (
    <Form.Item
      name={name}
      label={labelWithTooltip}
      rules={rules}
      className="app-text-field"
    >
      <Input
        type="text"
        placeholder={placeholder || (label ? (required ? `请输入${label}` : `请输入${label}（选填）`) : '')}
        maxLength={maxLength}
        showCount={maxLength !== undefined}
        className="text-field-input"
        data-testid={`text-field-${name}`}
      />
    </Form.Item>
  );
};

export default TextField;